#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# Copyright [Gtlions Lai].
# Create Date:
# Update Date:
"""GPDB 用户会话进程管理.

定期从GPDB扫描用户提交的清理会话进程请求并执行之

   Class(): summarization about Class
   ...
   function(): summarization about function
   ...
"""
from gtgpdb.pygresql.pgdb import *
import time

''' Crontab, must use shell sh with python'''
# os.system('source /usr/local/greenplum-gtdb/greenplum_path.sh')
# os.environ['PYTHONHOME'] = '/usr/local/greenplum-gtdb/./ext/python'
# print os.getenv('PYTHONHOME')
# sys.exit()


conn = connect(host='127.0.0.1', database='bigdatagp', user='gpadmin')
cursor = conn.cursor()
cursor.execute("select * from gpmg.proc_cron")
for o, p in cursor.fetchall():
    if o.lower() == 'c':
        exec_sql = "select pg_cancel_backend(" + str(p) + ")"
        cursor.execute(exec_sql)
        r = 'Succeed!'
        if cursor.fetchone()[0]:
            print r
            cursor.execute("insert into gpmg.proc_cron_log(oper_time,oper_result,oper,pid) values(%s, %s, %s, %s)",
                           (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), r, o, p))
            cursor.execute("delete from gpmg.proc_cron where oper=%s and pid=%s", (o, p))
            conn.commit()
        else:
            r = 'Failure!'
            print r + ' Wlii attempt 5 times. [PID = ' + str(p) + ' ]'
            for i in range(5):
                print str(i + 1) + ' Times. '
                cursor.execute(exec_sql)
                if cursor.fetchone()[0]:
                    r = 'Succeed!'
                    print r
                    break
                time.sleep(5)
                if i == 4:
                    print r + ' Yet attempt 5 times. [PID = ' + str(p) + ' ]'
            cursor.execute("insert into gpmg.proc_cron_log(oper_time,oper_result,oper,pid) values(%s, %s, %s, %s)",
                           (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), r, o, p))
            cursor.execute("delete from gpmg.proc_cron where oper=%s and pid=%s", (o, p))
            conn.commit()
    elif o.lower() == 'k':
        exec_sql = "select pg_terminate_backend(" + str(p) + ")"
        cursor.execute(exec_sql)
        r = 'Succeed!'
        if cursor.fetchone()[0]:
            print r
            cursor.execute("insert into gpmg.proc_cron_log(oper_time,oper_result,oper,pid) values(%s, %s, %s, %s)",
                           (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), r, o, p))
            cursor.execute("delete from gpmg.proc_cron where oper=%s and pid=%s", (o, p))
            conn.commit()
        else:
            r = 'Failure!'
            print r + ' Wlii attempt 5 times. [PID = ' + str(p) + ' ]'
            for i in range(5):
                print str(i + 1) + ' Times. '
                cursor.execute(exec_sql)
                if cursor.fetchone()[0]:
                    r = 'Succeed!'
                    print r
                    break
                time.sleep(5)
                if i == 4:
                    print r + ' Yet attempt 5 times. [PID = ' + str(p) + ' ]'
            cursor.execute("insert into gpmg.proc_cron_log(oper_time,oper_result,oper,pid) values(%s, %s, %s, %s)",
                           (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), r, o, p))
            cursor.execute("delete from gpmg.proc_cron where oper=%s and pid=%s", (o, p))
            conn.commit()
